import fs from 'fs'
import path from 'path'
import returnVuePath from '../utils/returnVuePath.js'
//重写ts和js的import路径
const complierVue = ({ root, app }) => {
    app.use(async (ctx, next) => {
        if (ctx.path.endsWith('.vue')) {
            let content = fs.readFileSync(path.join(root, ctx.path), 'utf-8')
            //获取sfc文件内容
            let src = returnVuePath(root).complierSfc
            let { parse, compileTemplate } = await import(`file://${src}`)
            let code = ''
            let script = parse(content).descriptor.script
            console.log(script.content, 'script');
            let template = parse(content).descriptor.template
            if (!ctx.query.type) {
                if (script.content) {
                    code += script.content.replace('export default', 'const __sfc_main =')
                }
                //分成两个文件
                if (template) {
                    const templateRequest = ctx.path + '?type=template'
                    code += `\nimport { render as __render } from '${templateRequest}'`
                    code += `\n__sfc_main.render = __render`
                }
                code += `\nexport default __sfc_main`
                ctx.type = 'js'
                ctx.body = code
            }
            if (ctx.query.type === 'template') {
                if (template) {
                    let templateCode = compileTemplate(template).code
                    ctx.type = 'js'
                    ctx.body = templateCode
                }
            }
        } else {
            await next()
        }
    })
}
export default complierVue